package com.zl.tby.service.impl;

import com.zl.tby.core.base.bean.TbyPageResult;
import com.zl.tby.core.base.util.ToolsUtil;
import com.zl.tby.core.common.R;
import com.zl.tby.dto.TbyUavInfoQuery;
import com.zl.tby.dto.TbyUavRecordQuery;
import com.zl.tby.model.TbyUavInfo;
import com.zl.tby.model.TbyUavRecord;
import com.zl.tby.repository.TbyUavRecordRepo;
import com.zl.tby.service.ITbyUavInfoService;
import com.zl.tby.service.ITbyUavRecordService;
import com.zl.tby.vo.TbyResearchActivitiesForm;
import com.zl.tby.vo.TbyUavInfoForm;
import com.zl.tby.vo.TbyUavRecordForm;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Tran;
import org.noear.wood.DbContext;
import org.noear.wood.IPage;
import org.noear.wood.annotation.Db;
import org.noear.wood.impl.IPageImpl;
import org.noear.wood.utils.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 无人机使用记录 接口实现类
 * @author changpeng
 * @version 1.0
 * @since 2024/8/6 20:22
 */
@Component
public class TbyUavRecordServiceImpl implements ITbyUavRecordService {

    @Db
    private TbyUavRecordRepo tbyUavRecordRepo;
    @Inject
    private ITbyUavInfoService tbyUavInfoService;
    @Db
    private DbContext db;

    @Override
    @Tran
    public R<TbyUavRecord> add(TbyUavRecordForm form) {
        TbyUavRecord entity = form.createEntity();
        entity.setCreateBy(ToolsUtil.getLoginUserId());
        entity.setCreateTime(LocalDateTime.now());
        long id = tbyUavRecordRepo.insert(entity, true);
        entity.setId(id);
        updateUavInfo(entity.getUavId());
        return R.ok(entity);
    }

    @Override
    @Tran
    public R<TbyUavRecord> update(TbyUavRecordForm form) {
        TbyUavRecord entity = this.get(form.getId());
        if (entity == null) {
            return R.failed("数据不存在");
        }
        form.updateEntity(entity);
        entity.setUpdateBy(ToolsUtil.getLoginUserId());
        entity.setUpdateTime(LocalDateTime.now());
        tbyUavRecordRepo.updateById(entity, false);
        updateUavInfo(entity.getUavId());
        return R.ok(entity);
    }

    @Override
    public int delete(Long id) {
        TbyUavRecord entity = this.get(id);
        if (entity != null) {
            updateUavInfo(entity.getUavId());
        }
        return tbyUavRecordRepo.deleteById(id);
    }

    @Override
    public TbyUavRecord get(Long id) {
        return tbyUavRecordRepo.selectById(id);
    }

    @Override
    public TbyPageResult<TbyUavRecordForm> page(TbyUavRecordQuery query) {
        IPage<TbyUavRecord> iPage = tbyUavRecordRepo.selectPage(query.getOffset(), query.getSize(), mp -> {
            mp.whereTrue()
                    .andIf(ToolsUtil.isNotNull(query.getUavId()), "uav_id = ? ", query.getUavId())
                    .andIf(StringUtils.isNotEmpty(query.getTaskCode()), "task_code = ?", query.getTaskCode())
                    .andIf(StringUtils.isNotEmpty(query.getUseDateBegin()), "use_date >= ?", query.getUseDateBegin())
                    .andIf(StringUtils.isNotEmpty(query.getUseDateEnd()), "use_date <= ?", query.getUseDateEnd());
            if (StringUtils.isNotEmpty(query.getOrder())) {
                mp.orderBy(query.getOrder());
            }
        });
        List<TbyUavInfo> uavList = this.tbyUavInfoService.list(new TbyUavInfoQuery());
        Map<Long, String> uavMap = new HashMap<>(0);
        for (TbyUavInfo uav : uavList) {
            uavMap.put(uav.getId(), uav.getName());
        }
        List<TbyUavRecordForm> formList = new ArrayList<>();
        iPage.getList().forEach(item -> {
            formList.add(TbyUavRecordForm.recordConvert(item, uavMap.get(item.getUavId())));
        });
        return new TbyPageResult(new IPageImpl(formList, iPage.getTotal(), iPage.getSize()), query);
    }

    @Override
    public List<TbyUavRecord> list(TbyUavRecordQuery query) {
        return tbyUavRecordRepo.selectList(mapperWhereQ -> {
            mapperWhereQ.whereTrue()
                    .andIf(ToolsUtil.isNotNull(query.getUavId()), "uav_id = ? ", query.getUavId())
                    .andIf(StringUtils.isNotEmpty(query.getTaskCode()), "task_code = ?", query.getTaskCode())
                    .andIf(StringUtils.isNotEmpty(query.getUseDateBegin()), "use_date >= ?", query.getUseDateBegin())
                    .andIf(StringUtils.isNotEmpty(query.getUseDateEnd()), "use_date <= ?", query.getUseDateEnd());
            if (StringUtils.isNotEmpty(query.getOrder())) {
                mapperWhereQ.orderBy(query.getOrder());
            }
        });
    }

    /**
     * 更新无人机的信息
     */
    private void updateUavInfo(Long uavId) {
        try {
            List<TbyUavInfoForm> uavList = db.table("tby_uav_record").whereEq("uav_id", uavId)
                    .selectList("uav_id id, count(id) flight_count, sum(flight_distance) flight_distance, sum(flight_time) flight_time", TbyUavInfoForm.class);
            if (uavList != null && uavList.size() > 0) {
                this.tbyUavInfoService.updateData(uavList.get(0));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
